package com.ziq.zcamp.manager

import com.blankj.utilcode.util.GsonUtils
import com.ziq.base.service.ConnectInfo
import com.ziq.base.service.ILongLinkListener
import com.ziq.base.service.LongLinkServiceWarp
import com.ziq.zcamp.api.service.LONG_LINK_URL

class LongLinkManager {

    companion object {
        val instance = SingletonHolder.holder
    }

    private object SingletonHolder {
        val holder= LongLinkManager()
    }

    private val mLongLinkServiceWarp = LongLinkServiceWarp(context = GlobalContextManager.appContext!!)
    private val pushListenerTypeMap = hashMapOf<IPushListener, Int>()
    private val pushListenerMap = hashMapOf<Int, MutableList<IPushListener>>()

    private val mPushManager : PushManager = PushManager()

    constructor(){
        mPushManager.registerPush(this)
    }

    fun getPushManager() : PushManager {
        return mPushManager
    }

    fun disconnect(){
        mLongLinkServiceWarp.disconnect()
    }

    fun connect(){
        if(mLongLinkServiceWarp.serviceBinder == null){
            mLongLinkServiceWarp.init(onServiceConnected = {
                mLongLinkServiceWarp.registerListener(object : ILongLinkListener.Stub() {
                    override fun onReceive(originBytes: ByteArray?, body: ByteArray?) {
                        try {
                            body?.let {
                                val item = GsonUtils.fromJson(String(it), BasePushMessage::class.java)
                                pushListenerMap[item.type]?.forEach { listener ->
                                    listener.onReceive(item.data)
                                }
                            }
                        } catch (e:Exception){
                            e.printStackTrace()
                        }
                    }
                })
                connectLongLink()
            })
        } else {
            connectLongLink()
        }
    }

    private fun connectLongLink(){
        mLongLinkServiceWarp.connect(ConnectInfo().apply {
            url = LONG_LINK_URL
            uid = UserManager.instance.getUid()
        })
    }

    @Synchronized
    fun registerPushListener(type : Int, listener : IPushListener){
        pushListenerTypeMap[listener] = type
        if(pushListenerMap[type] == null){
            pushListenerMap[type] = mutableListOf()
        }
        pushListenerMap[type]?.add(listener)
    }

    @Synchronized
    fun unregisterPushListener(listener : IPushListener){
        val type = pushListenerTypeMap[listener]
        pushListenerMap[type]?.remove(listener)
        pushListenerTypeMap.remove(listener)
    }


    interface IPushListener {
        fun onReceive(data : String)
    }

    class BasePushMessage {
        var type = 0
        var data = ""
    }

}